package com.lv.phuotbacnam.ui.fragment;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.android.gms.maps.model.LatLng;
import com.lv.phuotbacnam.R;
import com.lv.phuotbacnam.bl.callback.ThreadSafeResultCallback;
import com.lv.phuotbacnam.bl.data.BaiDangObject;
import com.lv.phuotbacnam.bl.log.Logger;
import com.lv.phuotbacnam.bl.log.Toaster;
import com.lv.phuotbacnam.bl.network.error.ApplicationError;
import com.lv.phuotbacnam.bl.queries.BaiDangQueries;
import com.lv.phuotbacnam.bl.queries.QueriesConstant;
import com.lv.phuotbacnam.bl.utils.IntentHelper;
import com.lv.phuotbacnam.toolbox.ImageUtils;
import com.lv.phuotbacnam.toolbox.JsonUtils;
import com.lv.phuotbacnam.ui.Constants;
import com.lv.phuotbacnam.ui.Section;
import com.lv.phuotbacnam.ui.activity.BackActivity;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseFile;
import com.parse.ParseObject;
import com.parse.SaveCallback;

public class SuaBaiDang extends BaseFragment {
	/* Load image activity result code */
	private final int RESULT_LOAD_IMAGE = 12323;

	/* Keys to define info of images */
	public static final String URL = "url";
	// public static final String NAME = "name";
	// public static final String TYPE = "__type";

	/* The info of all bitmaps that it was created from sdcard */
	JSONArray jsonArrayBitmap;

	/* The quantity of bitmaps that it was saved on Parse */
	int numberBitmapSaved = 0;

	public static LatLng vi_tri_da_chon;

	private ImageView currentExpectingImage;

	private Handler mHandler;

	/* The bitmaps that it was taken from sdcard */
	private Bitmap[] bitmaps;

	private int[] mListImageId = { R.id.cover_photo, R.id.add_image_one,
			R.id.add_image_two, R.id.add_image_three, R.id.add_image_four,
			R.id.add_image_five };

	/* List image was get from server */
	ArrayList<String> list_image_url_string;

	private EditText ten_bai_dang;
	private EditText cam_nhan;
	private EditText loi_khuyen;
	private TextView chon_dia_diem;
	private ImageView img_post;

	private ProgressBar pb_waiting;

	private ParseObject baidang;
	private ParseObject dia_diem;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_sua_bai_dang,
				container, false);

		try {
			baidang = (ParseObject) IntentHelper
					.getObjectForKey(Constants.KEY_BAI_DANG);
			dia_diem = baidang
					.getParseObject(QueriesConstant.TableBaiDang.COLUMN_dia_diem);

		} catch (Exception e) {
			errorGetBaiDang();
			return null;
		}

		initObject();

		ten_bai_dang = (EditText) rootView.findViewById(R.id.ten_bai_dang);
		cam_nhan = (EditText) rootView.findViewById(R.id.cam_nhan);
		loi_khuyen = (EditText) rootView.findViewById(R.id.loi_khuyen);
		chon_dia_diem = (TextView) rootView.findViewById(R.id.chon_dia_diem);
		pb_waiting = (ProgressBar) rootView.findViewById(R.id.pb_waiting);
		img_post = (ImageView) rootView.findViewById(R.id.img_post);

		// Show info on UI before updating
		showInfo(rootView);

		chon_dia_diem.setOnClickListener(myOnClickListener);
		rootView.findViewById(R.id.img_post).setOnClickListener(
				myOnClickListener);

		rootView.findViewById(R.id.cover_photo).setOnClickListener(
				imageGetOnClickListener);
		rootView.findViewById(R.id.add_image_one).setOnClickListener(
				imageGetOnClickListener);
		rootView.findViewById(R.id.add_image_two).setOnClickListener(
				imageGetOnClickListener);
		rootView.findViewById(R.id.add_image_three).setOnClickListener(
				imageGetOnClickListener);
		rootView.findViewById(R.id.add_image_four).setOnClickListener(
				imageGetOnClickListener);
		rootView.findViewById(R.id.add_image_five).setOnClickListener(
				imageGetOnClickListener);

		return rootView;
	}

	/**
	 * To show info of diadiem before updating
	 */
	private void showInfo(View rootView) {
		dia_diem.fetchIfNeededInBackground(new GetCallback<ParseObject>() {
			@Override
			public void done(ParseObject diadiem, ParseException arg1) {
				chon_dia_diem.setHint(diadiem
						.getString(QueriesConstant.TableDiaDiem.COLUMN_ten_dia_diem));
			}
		});

		ten_bai_dang.setText(baidang
				.getString(QueriesConstant.TableBaiDang.COLUMN_ten_bai_dang));
		cam_nhan.setText(baidang
				.getString(QueriesConstant.TableBaiDang.COLUMN_cam_nhan));
		loi_khuyen.setText(baidang
				.getString(QueriesConstant.TableBaiDang.COLUMN_loi_khuyen));

		// Show List Image
		JSONArray list_image_url = baidang
				.getJSONArray(QueriesConstant.TableBaiDang.COLUMN_list_photo);
		list_image_url_string = JsonUtils.getStringList(list_image_url, "url");
		for (int i = 0; i < list_image_url_string.size(); i++) {
			imageLoader.showImage(
					(ImageView) rootView.findViewById(mListImageId[i]),
					list_image_url_string.get(i));
		}
	}

	/**
	 * To init object
	 */
	private void initObject() {
		bitmaps = new Bitmap[6];
		jsonArrayBitmap = new JSONArray();
		mHandler = new Handler();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		vi_tri_da_chon = null;
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	@Override
	public void applyStyles() {
		super.applyStyles();
		getNavigationController().getNavigationBar().setActionTitle(
				getString(R.string.chinh_sua_bai_dang));

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		// Get the selected image
		if (requestCode == RESULT_LOAD_IMAGE
				&& resultCode == Activity.RESULT_OK && null != data) {
			ImageUtils.decodeFromUri(
					getActivity(),
					data.getData(),
					new ThreadSafeResultCallback<Object, Bitmap>(Looper
							.getMainLooper()) {

						@Override
						public void doOnSuccess(Object request, Bitmap result) {
							/* show current expecting image to image view */
							currentExpectingImage.setImageBitmap(result);

							/* add bitmap to array list */
							for (int i = 0; i < mListImageId.length; i++)
								if (currentExpectingImage.getId() == mListImageId[i])
									bitmaps[i] = result;
						}

						@Override
						public void doOnError(ApplicationError error) {
						}
					});
		}
	}

	/**
	 * Handle onclick for image
	 */
	private View.OnClickListener imageGetOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			currentExpectingImage = (ImageView) v;
			Intent i = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(i, RESULT_LOAD_IMAGE);
		}
	};

	/**
	 * Handle onclick for others view
	 */
	private View.OnClickListener myOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.chon_dia_diem:
				getNavigationController().navigateTo(BackActivity.class, false,
						Section.GOOGLE_MAP_CHON_VI_TRI, null);
				break;

			case R.id.img_post:
				getValue();
				break;

			default:
				break;
			}
		}

		/**
		 * To get data from ui
		 */
		private void getValue() {
			String ten_bai_dang_value = ten_bai_dang.getText().toString()
					.trim();
			String cam_nhan_value = cam_nhan.getText().toString().trim();
			String loi_khuyen_value = loi_khuyen.getText().toString().trim();
			String chon_dia_diem_value = chon_dia_diem.getText().toString()
					.trim();

			// TODO
			// test
			chon_dia_diem_value = "Nha tho duc ba";

			//
			// Logger.logMessage("getValue");
			// Logger.logMessage("ten dia diem : " + ten_dia_diem_value);
			// Logger.logMessage("ten_bai_dang_value : " + ten_bai_dang_value);
			// Logger.logMessage("cam_nhan_value : " + cam_nhan_value);
			// Logger.logMessage("loi_khuyen_value : " + loi_khuyen_value);
			// Logger.logMessage("vi_tri_value : " + vi_tri_value);
			// Logger.logMessage("seekBarValue_value : " + seekBarValue_value);

			if (chon_dia_diem_value.equals("")) {
				chon_dia_diem.requestFocus();
				Toaster.showToast(getActivity(),
						getString(R.string.ban_phai_nhap)
								+ getString(R.string.vi_tri));
			} else if (ten_bai_dang_value.equals("")) {
				ten_bai_dang.requestFocus();
				Toaster.showToast(getActivity(),
						getString(R.string.ban_phai_nhap)
								+ getString(R.string.ten_bai_dang));
			} else if (cam_nhan_value.equals("")) {
				cam_nhan.requestFocus();
				Toaster.showToast(getActivity(),
						getString(R.string.ban_phai_nhap)
								+ getString(R.string.cam_nhan));
			} else if (loi_khuyen_value.equals("")) {
				loi_khuyen.requestFocus();
				Toaster.showToast(getActivity(),
						getString(R.string.ban_phai_nhap)
								+ getString(R.string.loi_khuyen));
			} else if (jsonArrayBitmap == null)
				Toaster.showToast(getActivity(),
						getString(R.string.ban_phai_chon_photo));
			else {
				BaiDangObject baiDangObject = new BaiDangObject(
						ten_bai_dang_value, jsonArrayBitmap, cam_nhan_value,
						loi_khuyen_value);
				// DiaDiemObject diaDiemObject = new DiaDiemObject(
				// ten_dia_diem_value, vi_tri_geoXY, 1, 1, 1,
				// diem_binh_chon);
				saveData(baiDangObject);
			}
		}
	};

	/**
	 * To save an image to Parse sever and get the info
	 */
	public void createImageParseFile(Bitmap bm) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
		final ParseFile pFile = new ParseFile("file", stream.toByteArray());
		pFile.saveInBackground(new SaveCallback() {
			@Override
			public void done(ParseException arg0) {
				try {
					JSONObject anImageObjec = new JSONObject();
					anImageObjec.put(URL, pFile.getUrl());
					// anImageObjec.put(NAME, pFile.getName());
					// anImageObjec.put(TYPE, "File");
					jsonArrayBitmap.put(anImageObjec);
				} catch (Exception e2) {
					Logger.logMessage("createImageParseFile Error");
				}
				numberBitmapSaved += 1;
			}
		});
	}

	/**
	 * To save KOEvent to Parse
	 */
	public void saveData(final BaiDangObject baiDangObject) {
		img_post.setVisibility(View.GONE);
		pb_waiting.setVisibility(View.VISIBLE);

		/* Save each bitmap to Parse server */
		for (int i = 0; i < bitmaps.length; i++)
			if (bitmaps[i] != null)
				createImageParseFile(bitmaps[i]);
			else {
				try {
					if (list_image_url_string.get(i) != null) {
						JSONObject anImageObjec = new JSONObject();
						anImageObjec.put(URL, list_image_url_string.get(i));
						// anImageObjec.put(NAME, pFile.getName());
						// anImageObjec.put(TYPE, "File");
						jsonArrayBitmap.put(anImageObjec);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

				numberBitmapSaved += 1;
			}

		/* Check the number of bitmap that it was saved on Parse */
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				if (numberBitmapSaved >= bitmaps.length) {
					img_post.setVisibility(View.VISIBLE);
					pb_waiting.setVisibility(View.GONE);
					Toaster.showToast(getActivity(),
							getString(R.string.dang_bai_thanh_cong));
					// TODO test nen de dia diem la null
					BaiDangQueries.updateBaiDang(baidang, baiDangObject, null);
					mHandler.removeCallbacks(this);
				} else
					mHandler.postDelayed(this, 500);
			}
		});
	}

	/**
	 * Xu ly khi get bai dang bi loi
	 */
	private void errorGetBaiDang() {
		Toaster.showToast(getActivity(), getString(R.string.thong_tin_bi_loi));
		getActivity().finish();
	}
}
